package cn.tedu.system.base.listener;
import cn.tedu.system.base.util.AddressUtils;
import cn.tedu.system.base.util.IpUtils;
import cn.tedu.system.base.util.WebUtils;
import cn.tedu.system.log.pojo.LoginInfor;
import cn.tedu.system.log.service.LoginInforService;
import lombok.extern.slf4j.Slf4j;
import nl.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Slf4j
@Component
public class AuthenticationSuccessListener
    implements ApplicationListener<AuthenticationSuccessEvent> {
    @Autowired
    private LoginInforService loginInforService;
    //当我们使用了@Sl4j注解后，可以直接使用log对象,不需要我们自己再创建了
    //private static final Logger log= LoggerFactory.getLogger(AuthenticationSuccessListener.class);
    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {
        //获取认证对象的凭证信息
        Object principal = event.getAuthentication().getPrincipal();
        if(principal instanceof UserDetails){
            String username=((UserDetails)principal).getUsername();
            saveLoginInfor(username);
        }
    }
    private void saveLoginInfor(String username){
        log.info("{}认证成功",username);
        HttpServletRequest request = WebUtils.getRequest();
        UserAgent userAgent =
        UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        // 获取客户端操作系统
        String os = userAgent.getOperatingSystem().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        System.out.println("os="+os+"browser="+browser);
        //获取ip地址以及位置
        request.getRemoteAddr();
        String ip = IpUtils.getIpAddress(request);
        String region= AddressUtils.getIpRegion(ip);
        LoginInfor loginInfor=new LoginInfor();
        loginInfor.setLoginName(username);
        loginInfor.setBrowser(browser);
        loginInfor.setOs(os);
        loginInfor.setIpaddr(ip);
        loginInfor.setLoginLocation(region);
        loginInfor.setStatus("0");
        loginInfor.setLoginTime(new Date());
        loginInfor.setMsg("login ok");
        loginInforService.save(loginInfor);
    }
}
